// pages/transportConfirm/index.js
import requestUtil from '../../../baseRequest.js'
import requestUrls from '../../../requestUrl.js'
import { $Message } from '../../../components/base/index'
import commonUtils from '../../../utils/util.js'
let openid = wx.getStorageSync('openid')
let formTempObject = {}
const uploadUrlCommons = '/api/insurance/image/upload'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    openid: openid,
    transportConfirm: {},
    isUploadGoodsPhotos: false,
    signKey: 'driverSignature',
    uploadGoodsPhoto: {
      itemType: 'uploader',
      title: '货物照片',
      name: 'goodsPhotos',
      files: [],
      count: 30,
      uploadUrl: requestUrls.baseUrl + uploadUrlCommons,
      isUpload: false,
      uploadComplete: 'completeUserCarImgsUpload',
      attentionText: '货物照片最多上传30张图片',
      sourceType: 'camera', //'all/camera'
    },
    originGoodsPhotoList: [],
    payMethodList: [{ "id": 1, "name": "现金" }, { "id": 2, "name": "月结" }],
    payerList: [{ "id": 1, "name": "委托方" }, { "id": 2, "name": "接收方" }],
    unloadedMethodList: [{ "id": 1, "name": "承运方" }, { "id": 2, "name": "接收方" }],
    //是否提交过
    isSubmit: false,
    agreementChecked: true
  },
  completeUserCarImgsUpload(e) {
    console.log("获取信息回调-->", e)
    let detail = e.detail
    let status = detail.status
    if (status || status == 'error') {
      this.showErrorMessage("货物相片上传失败，请重新选择上传");
      console.log("货物相片上传失败，请重新选择上传")
      this.setData({
        showSpin: false,
        ['formParam.goodsPhotos']: [],
        ['uploadGoodsPhoto.isUpload']: false,
      })
      return
    }

    console.log("formParam", this.data.formParam)
    this.setData({
      ['formParam.goodsPhotos']: detail
    })
    this.saveStep2();
  },
  /**获取救援司机信息 */
  getDetail() {
    //原始逻辑
    if (this.data.truckOrderId === null || this.data.truckOrderId === undefined) {
      if (!this.data.openid) {
        this.setData({
          openid: wx.getStorageSync('openid')
        })
      }
      if (this.data.id) {
        let param = {
          'openid': this.data.openid,
          'id': this.data.id
        }
        let url = requestUrls.transportConfirm.load
        requestUtil.postRequest(url, param, (res) => {
          let info = res
          this.setData({
            transportConfirm: info
          })
        }, () => { })
      }
    } else {
      //如果传入数据不为空，则查询数据库，获取自动生成的运输确认单信息
      const formData = {
        openId: this.data.openid,
        criteria: {
          id: this.data.truckOrderId
        }
      };
      requestUtil.postRequest(requestUrls.truckOrder.getById, formData, (res) => {
        this.setData({
          transportConfirm: res.result.transportConfirmForm,
          id: res.result.transportConfirmForm.id,
          editable: true,
        })
      })
    }
  },
  handleChange({ detail = {} }) {
    console.log('handleChange', detail)
    formTempObject[detail.key] = detail.value
  },
  /**第二部*/
  saveStep2() {
    let param = this.data.formParam
    let url = requestUrls.transportConfirm.stepTwo
    console.log('param', param, 'url', url)
    // let goodsPhotos =  param.goodsPhotos;
    // if (goodsPhotos || goodsPhotos.length>0){

    //   let goodsPhotoList = goodsPhotos.map((item,index,arr)=>{
    //       return item.url;
    //   });
    //   param.goodsPhotos = goodsPhotoList;

    // }
    param.id = this.data.id
    param.openid = this.data.openid
    requestUtil.postRequest(url, param, (res) => {
      this.setData({
        showSpin: false
      })
      if (res.code == 10012) {
        this.setData({
          isSubmit: true
        })
        wx.showModal({
          title: '提交失败',
          content: res.message,
          showCancel: false,
          success: res => { }
        })
        return
      }
      // if (res.isFail) {
      //   wx.showModal({
      //     title: '提交失败',
      //     content: res.msg,
      //     showCancel: false,
      //     success: res => { }
      //   })
      //   return
      // }
      //进入第二步，填写接货确认单
      wx.reLaunch({
        url: '../complete/index?id=' + res.id
      })
    }, () => { })

  },

  /**提交表单信息 */
  submitForm(event) {
    let data = event.detail.value;
    const optType = event.detail.target.dataset.opt;
    if (optType && optType === 'next') {
      if (this.checkFormData(event.detail.value)) {
        if (this.data.isSubmit) {
          this.setData({
            showSpin: true,
            formParam: data,
          })
          this.saveStep2()
        } else {
          this.setData({
            ['uploadGoodsPhoto.isUpload']: true,
            showSpin: true,
            formParam: data,
            //['formParam.openid']: this.data.openid
          })
        }
        // 返回顶部
        wx.pageScrollTo({
          scrollTop: 0,
        })
      }
    }else if(optType==='complain'){
    //跳转到仲裁单创建页面
    wx.navigateTo({
      url:'/pages/arbitration/create/index?publishSide='+this.data.publishSide+"&transportConfirmFormId="+this.data.id
    });
    }else if(optType==='cancel'){
        //车主取消装货
        const formData = {
          openId: this.data.openid,
          criteria: {
            truckOrderId: this.data.truckOrderId
          }
        };
        requestUtil.postRequest(requestUrls.truckOrder.driverCancel, formData, (res) => {
          if (!res.hasError) {
            wx.showModal({
              title: '温馨提示',
              content: '操作成功',
              showCancel: false,
              success: res => {
                wx.switchTab({
                  url:'/pages/home/index2'
                })
              }
          })
          }
        })
    }
  },

  /**检查表单信息 */
  checkFormData(data) {
    // return false
    if (!data.clientName || commonUtils.trim(data.clientName).length == 0) {
      this.showErrorMessage('委托方姓名不能为空')
      return false
    }
    if (!data.clientPhone || commonUtils.trim(data.clientPhone).length == 0) {
      this.showErrorMessage('委托方电话不能为空')
      return false
    } else if (!commonUtils.checkTelphoneNumber(data.clientPhone)) {
      this.showErrorMessage('委托方电话格式有误，请重新输入')
      return false
    }
    if (!data.receiverName || commonUtils.trim(data.receiverName).length == 0) {
      this.showErrorMessage('收货方姓名不能为空')
      return false
    }
    if (!data.receiverPhone || commonUtils.trim(data.receiverPhone).length == 0) {
      this.showErrorMessage('收货方电话不能为空')
      return false
    } else if (!commonUtils.checkTelphoneNumber(data.receiverPhone)) {
      this.showErrorMessage('收货方电话格式有误，请重新输入')
      return false
    }
    if (!data.receiverAddr || commonUtils.trim(data.receiverAddr).length == 0) {
      this.showErrorMessage('收货方地址不能为空')
      return false
    }
    if (!data.transports || commonUtils.trim(data.transports).length == 0) {
      this.showErrorMessage('运输物不能为空')
      return false
    }
    if (!data.amount) {
      this.showErrorMessage('请输入运费')
      return false
    }
    if (!commonUtils.isMoney(data.amount)) {
      this.showErrorMessage('金额格式不正确')
      return false
    }
    if (!data.driverSignature || data.driverSignature == '') {
      this.showErrorMessage('签名不能为空')
      return false
    }

    if (commonUtils.isEmoji(data.addr)) {
      this.showErrorMessage('地址不能带有表情字符')
      return false
    }
    return true
  },
  changeAgreementCheckBox(e) {
    console.log(e)
    this.setData({
      agreementChecked: !this.data.agreementChecked
    })
  },
  /**显示错误信息 */
  showErrorMessage(msg) {
    $Message({
      content: msg,
      type: 'error'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { id, truckOrderId } = options;
    this.setData({
      id: id,
      truckOrderId: truckOrderId,
    })
    //获取数据
    this.getDetail()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      signPaths: getApp().globalData.signTempPath,
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    getApp().cleanSignTempPathCache()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function() {

  // }
})
